package gui.edt.swingutilities;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Executor;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class LoopEDT extends JFrame {

	private JButton bStart;
	private JLabel lText;

	private final String CST_NUMBER = "Number : ";

	public LoopEDT() {
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setLocationRelativeTo(null);
		setLayout(new BorderLayout());

		// adding components
		addComponent();

		// managing events
		manageEvent();

		pack();
	}

	private void addComponent() {
		lText = new JLabel(CST_NUMBER);
		bStart = new JButton("Start");
		add(lText, BorderLayout.NORTH);
		add(bStart, BorderLayout.SOUTH);
	}

	private void manageEvent() {
		final Executor executor = new Executor() {

			@Override
			public void execute(Runnable command) {
				// TODO Auto-generated method stub
				new Thread(command).start();
			}
		};
		bStart.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				DoAction doAction = new DoAction();
				// Thread tAction = new Thread(doAction);
				// doAction.setThreadID(tAction);
				// tAction.start();
				executor.execute(doAction);
			}
		});
	}

	private class DoAction implements Runnable {
		@Override
		public void run() {
			doAction();
		}

		private Thread t;

		private void setThreadID(Thread threadID) {
			this.t = threadID;
		}

		private void doAction() {
			System.out.print(Thread.currentThread().getName());
			// System.out.println("\t" + t.getName());
			// System.out.println(t.getName().equals(
			// Thread.currentThread().getName()));
			final int[] cpt = new int[1];
			for (int i = 1; i < 1001; i++) {
				cpt[0] = i;
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				SwingUtilities.invokeLater(new Runnable() {

					@Override
					public void run() {
						lText.setText(CST_NUMBER + cpt[0]);
						pack();
					}
				});
			}
		}
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new LoopEDT().setVisible(true);
			}
		});
	}
	
	private void incrementLabel(final int tick[], final JLabel label) {
		tick[0]++;
		Runnable code = new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				label.setText("" + tick[0]++);
			}
		};
		
		if (SwingUtilities.isEventDispatchThread()) {
			code.run();
		} else {
			SwingUtilities.invokeLater(code);
		}
	}
}
